package net.qhzw.geologr5.gis.common.security.service;

import net.qhzw.geologr5.gis.common.framework.exception.CustomException;
import net.qhzw.geologr5.gis.common.security.entity.LoginUser;
import net.qhzw.geologr5.gis.api.system.UserClient;
import net.qhzw.geologr5.gis.api.system.entity.User;
import net.qhzw.geologr5.gis.api.system.entity.UserInfo;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户信息处理
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserClient userClient;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            JsonResult<UserInfo> userResult = userClient.getInfoByName(username);
            checkUser(userResult, username);
            UserInfo userInfo = userResult.getData();
            User user = userInfo.getSysUser();
            if (user.getMark() == 0) {
                log.info("登录用户：{} 已锁定", username);
                throw new CustomException("登录用户：" + username + " 已锁定请联系管理员", 501);
            }
            return getUserDetails(userResult);
        }catch (CustomException e) {
            log.error("登录异常: {}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }catch (Exception e) {
            log.error("登录异常: {}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }

    }

    private UserDetails getUserDetails(JsonResult<UserInfo> result) {
        try {
            UserInfo info = result.getData();
            Set<String> dbAuthsSet = new HashSet<String>();
            if (StringUtils.isNotEmpty(info.getRoles())) {
                // 获取角色
                dbAuthsSet.addAll(info.getRoles());
                dbAuthsSet.addAll(info.getPermissions());
            }
            Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                    .createAuthorityList(dbAuthsSet.toArray(new String[0]));
            User user = info.getSysUser();
            return new LoginUser(user.getId(), user.getUsername(), user.getPassword(),
                    true, true, true, true, authorities);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    public void checkUser(JsonResult userResult, String username) {
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("登录用户：" + username + " 不存在");
        }
    }


}
